<template>
    <div class="wage-calculator">
        <h1>牛马收益</h1>
        <div class="calculator-container">
            <p class="description">您工作的性价比为：</p>
            <!-- 绑定样式 -->
            <p class="value" :style="{ color: getValueColor() }">{{ resultFactor }}</p>
            <!-- <hr /> -->
            <div class="dashed-line"></div>
            <div class="suggestion">
                <div class="suggestion-left" v-if="resultFactor <= 0.8">
                    <img src="../../assets/img/indexImg8.jpeg" alt="图" class="image" />
                </div>
                <div class="suggestion-left" v-if="resultFactor > 0.8 && resultFactor <= 1.5">
                    <img src="../../assets/img/indexImg7.jpg" alt="图" class="image" />
                </div>
                <div class="suggestion-left" v-if="resultFactor > 1.5 && resultFactor <= 2.0">
                    <img src="../../assets/img/indexImg9.jpg" alt="图" class="image" />
                </div>
                <div class="suggestion-left" v-if="resultFactor > 2.0">
                    <img src="../../assets/img/indexImg6.jpg" alt="图" class="image" />
                </div>
                <div class="suggestion-right">
                    <div class="suggestion-one" v-if="resultFactor <= 0.8">
                        <p>您目前的工作可能不太开心呢</p>
                    </div>
                    <div class="suggestion-one" v-if="resultFactor > 0.8 && resultFactor <= 1.5">
                        <p>您目前的工作已经很好啦</p>
                    </div>
                    <div class="suggestion-one" v-if="resultFactor > 1.5 && resultFactor <= 2.0">
                        <p>您目前的工作肯定非常爽</p>
                    </div>
                    <div class="suggestion-one" v-if="resultFactor > 2.0">
                        <p>有点羡慕了~~</p>
                    </div>
                    <div class="suggestion-ai">
                        <!-- 显示接口回复 -->
                        <p>{{ aiSuggestion }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                result: '',
                avgSalary: 0,
                comEnvFactor: 0,
                resultFactor: 0,
                // 新增数据项，用于存储接口回复
                aiSuggestion: ''
            };
        },
        methods: {
            // 根据 resultFactor 返回对应的颜色
            getValueColor() {
                if (this.resultFactor <= 0.8) {
                    return 'rgb(255,83,64)';
                } else if (this.resultFactor > 0.8 && this.resultFactor <= 1.5) {
                    return 'rgb(255,139,187)';
                } else if (this.resultFactor > 1.5 && this.resultFactor <= 2.0) {
                    return 'rgb(62,192,30)';
                } else {
                    return 'rgb(67,129,255)';
                }
            },
            // 新增方法，用于向接口发送请求
            async sendAIRequest() {
                let question = '';
                if (this.resultFactor <= 0.8) {
                    question = '我的工作不是很好怎么办？请用100字回复我';
                } else if (this.resultFactor > 0.8 && this.resultFactor <= 1.5) {
                    question = '我的工作很一般怎么办？请用100字回复我';
                } else if (this.resultFactor > 1.5 && this.resultFactor <= 2.0) {
                    question = '我的工作不是特别好怎么办？请用100字回复我';
                } else {
                    question = '我的工作非常好怎么办？请用100字回复我';
                }

                const history = [
                    {
                        "role": "system",
                        "content": "你是一个智能助理，你的回答总是正确的、有用的和内容非常精简."
                    },
                    {
                        "role": "user",
                        "content": question
                    }
                ];

                try {
                    const response = await fetch('http://localhost:8000/v1/chat/completions', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            model: "local-model",
                            messages: history,
                            temperature: 0.7,
                            stream: true
                        })
                    });

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder('utf-8');
                    let assistantMessage = '';
                    let partialChunk = '';

                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        const chunk = decoder.decode(value);
                        const lines = (partialChunk + chunk).split('\n');
                        partialChunk = lines.pop();

                        for (const line of lines) {
                            if (line.startsWith('data: ')) {
                                const data = line.slice(6);
                                if (data === '[DONE]') break;

                                try {
                                    const json = JSON.parse(data);
                                    if (json.choices[0].delta.content) {
                                        const content = json.choices[0].delta.content;
                                        assistantMessage += content;
                                    }
                                } catch (error) {
                                    console.error('解析 JSON 出错:', error);
                                }
                            }
                        }
                    }

                    // 将接口回复存储到数据项中
                    this.aiSuggestion = assistantMessage;
                } catch (error) {
                    console.error('请求出错:', error);
                    this.aiSuggestion = '请求出错，请稍后重试。';
                }
            }
        },
        created() {
            const query = this.$route.query;
            const requiredFields = ['monthlySalary', 'dailyWorkHours', 'workDays', 'commuteTime', 'leisureTime', 'education', 'workEnv', 'attractiveEnv', 'colleagueEnv'];
            for (const field of requiredFields) {
                if (!query[field]) {
                    window.alert('检测到传入数据有空值，请重新输入。');
                    this.$router.back();
                    return;
                }
            }
            // 将所有传入的值转换为数字类型
            for (const key in query) {
                if (query.hasOwnProperty(key)) {
                    query[key] = Number(query[key]);
                }
            }
            // 验证 dailyWorkHours、commuteTime、leisureTime 在 0 - 24 之间
            if (query.dailyWorkHours < 0 || query.dailyWorkHours > 24) {
                window.alert('每天工作小时数必须是 0 - 24 之间的数字。');
                this.$router.back();
                return;
            }
            if (query.commuteTime < 0 || query.commuteTime > 24) {
                window.alert('每天通勤时间必须是 0 - 24 之间的数字。');
                this.$router.back();
                return;
            }
            if (query.leisureTime < 0 || query.leisureTime > 24) {
                window.alert('每天摸鱼时长必须是 0 - 24 之间的数字。');
                this.$router.back();
                return;
            }
            // 验证 workDays 在 0 - 32 之间
            if (query.workDays < 0 || query.workDays > 32) {
                window.alert('当月上班天数必须是 0 - 32 之间的数字。');
                this.$router.back();
                return;
            }

            // 替换 education 的值
            const educationMap = {
                1: 0.8,
                2: 1.0,
                3: 1.2,
                4: 1.4,
                5: 1.6,
                6: 1.8,
                7: 2.0
            };
            if (query.education) {
                query.education = educationMap[query.education] || query.education;
            }

            // 替换 workEnv 的值
            const workEnvMap = {
                1: 0.8,
                2: 0.9,
                3: 1.0,
                4: 1.1
            };
            if (query.workEnv) {
                query.workEnv = workEnvMap[query.workEnv] || query.workEnv;
            }

            // 替换 attractiveEnv 的值
            const attractiveEnvMap = {
                5: 0.9,
                6: 1.0,
                7: 1.1
            };
            if (query.attractiveEnv) {
                query.attractiveEnv = attractiveEnvMap[query.attractiveEnv] || query.attractiveEnv;
            }

            // 替换 colleagueEnv 的值
            const colleagueEnvMap = {
                8: 0.95,
                9: 1.0,
                10: 1.05
            };
            if (query.colleagueEnv) {
                query.colleagueEnv = colleagueEnvMap[query.colleagueEnv] || query.colleagueEnv;
            }

            // 计算平均日薪
            if (query.monthlySalary && query.workDays) {
                this.avgSalary = query.monthlySalary / query.workDays;
            }

            // 计算环境系数
            if (query.workEnv && query.attractiveEnv && query.colleagueEnv) {
                this.comEnvFactor = query.workEnv * query.attractiveEnv * query.colleagueEnv;
            }

            // 计算最终结果
            if (query.dailyWorkHours && query.commuteTime && query.leisureTime && query.education) {
                const denominator = 35 * (query.dailyWorkHours + query.commuteTime - 0.5 * query.leisureTime);
                if (denominator !== 0) {
                    this.resultFactor = (this.avgSalary * this.comEnvFactor) / denominator * query.education;
                    // 保留两位小数
                    this.resultFactor = parseFloat(this.resultFactor.toFixed(2));
                } else {
                    console.error('分母不能为零，请检查输入数据。');
                }
            }

            this.result = JSON.stringify(query, null, 2);
            console.log(query);
            console.log(this.resultFactor);

            // 调用发送请求的方法
            this.sendAIRequest();
        }
    };
</script>

<style scoped>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    .wage-calculator {
        width: 100vw;
        height: 100vh;
        background-color: #888;
        padding: 20px;
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    h1 {
        color: white;
        width: 548px;
        height: 157px;
        font-size: 100px;
        font-family: STXinwei;
    }

    .calculator-container {
        width: 80%;
        height: 80%;
        background-color: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }


    .dashed-line {
        width: 100%;
        height: 30px;
        border-bottom: 10px dashed black;
        margin-bottom: 10px;
    }

    .description {
        width: 100%;
        height: 20%;
        color: #d3a02f;
        font-size: 64px;
    }

    .value {
        /* 移除原有的颜色设置 */
        font-size: 64px;
        margin: 10px 0;
    }

    hr {
        margin: 20px 0;
        border: 1px solid black;
    }

    .suggestion {
        width: 80%;
        height: 80%;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .suggestion-left {
        width: 300px;
        height: 300px;
        display: flex;
    }

    .image {
        width: 100%;
        height: 100%;
    }

    .suggestion-right {
        width: 60%;
        height: 300px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .suggestion-one {
        width: 100%;
        height: 30%;
        font-size: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .suggestion-ai {
        width: 100%;
        height: 70%;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 5px dashed #ccc;
        /* 修改以下样式 */
        overflow: auto;
        text-overflow: clip;
        white-space: normal;
        padding: 10px;
        /* 可选，添加内边距让文字不紧贴边框 */
    }

    .suggestion-ai p {
        max-width: 100%;
        /* 确保文字不超出容器宽度 */
    }

    p {
        margin: 5px 0;
        color: #d3a02f;
    }
</style>